const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const { YtDlp } = require('ytdlp-nodejs');
const { getVideoUrl, downloadVideo: customDownloadVideo } = require('./dy_downloader.js');

let mainWindow;

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  });

  mainWindow.loadFile('index.html');
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

ipcMain.handle('download-video', async (event, { url: videoUrl, platform }) => {
  const selectedPlatform = String(platform || 'generic');
  const downloadsPath = path.join(app.getPath('downloads'), 'multi-downloader-js-downloads');
  if (!fs.existsSync(downloadsPath)) fs.mkdirSync(downloadsPath, { recursive: true });
  
  try {
    event.sender.send('download-progress', { status: 'starting', message: `开始下载：${selectedPlatform}平台...`, percent: 0 });

    if (selectedPlatform === 'douyin') {
      event.sender.send('download-progress', { status: 'info', message: `使用专用抖音下载器...`, percent: 0 });
      const finalVideoUrl = await getVideoUrl(videoUrl);
      event.sender.send('download-progress', { status: 'info', message: `已获取无水印视频链接...`, percent: 0 });
      
      const urlFileNameMatch = videoUrl.match(/\/video\/(\d+)/);
      const videoId = urlFileNameMatch ? urlFileNameMatch[1] : Date.now();
      const fileName = `douyin_video_${videoId}.mp4`;
      const savePath = path.join(downloadsPath, fileName);
      
      await customDownloadVideo(finalVideoUrl, savePath, (progress) => {
        const percent = progress.percent || 0;
        const message = `下载中: ${percent}% (${(progress.downloaded / 1024 / 1024).toFixed(2)} MB / ${(progress.total / 1024 / 1024).toFixed(2)} MB)`;
        event.sender.send('download-progress', { status: 'progress', message: message, percent: percent });
      });

      event.sender.send('download-progress', { status: 'completed', message: `抖音视频下载成功，保存至：${savePath}`, percent: 100 });
      return { success: true };

    } else {
      const outputPathTemplate = path.join(downloadsPath, '%(title)s [%(id)s].%(ext)s');
      const options = {
        format: 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
        output: outputPathTemplate,
        onProgress: (progress) => {
          const percent = progress.percent || 0;
          let message = `下载中: ${percent}%`;
          if (progress.speed) message += ` | 速度: ${progress.speed}`;
          if (progress.eta) message += ` | 剩余时间: ${progress.eta}`;
          event.sender.send('download-progress', { status: 'progress', message: message, percent: percent });
        },
      };

      const ytdlp = new YtDlp();
      const result = await ytdlp.downloadAsync(videoUrl, options);
      event.sender.send('download-progress', { status: 'completed', message: `下载完成！已保存至：${downloadsPath}`, percent: 100 });
      return { success: true, result };
    }

  } catch (error) {
    console.error('下载错误:', error);
    event.sender.send('download-progress', { status: 'error', message: `下载失败: ${error.message}`, percent: 0 });
    return { success: false, error: error.message };
  }
});